package mapkit.handlers
{
	import flash.events.MouseEvent;
	import flash.geom.Point;

	import mapkit.MapHandler;
	import mapkit.carto.Location;

	import mx.core.IFactory;
	import mx.core.UIComponent;

	public class MousePosition extends MapHandler
	{
		private var _content:UIComponent=null;

		private var _renderer:IFactory=null;

		public function get contentRenderer():IFactory
		{
			return _renderer;
		}

		public function set contentRenderer(value:IFactory):void
		{
			_renderer=value;
		}

		private var _where:Location=new Location();

		public function get where():Location
		{
			return _where;
		}

		[Bindable]
		public function set where(value:Location):void
		{
			_where=value;
		}

		override protected function load():void
		{
			super.load();
			map.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);

			if (!_content && _renderer)
			{
				var rawContent:Object=_renderer.newInstance();
				rawContent.data=this;
				if (rawContent is UIComponent)
				{
					_content=rawContent as UIComponent;
				}
			}

			if (_content)
			{
				if (map.acetate.contains(_content))
				{
					map.acetate.removeChild(_content);
				}
				map.acetate.addChild(_content);
			}
		}

		override protected function unload():void
		{
			if (_content)
			{
				if (map.acetate.contains(_content))
				{
					map.acetate.removeChild(_content);
				}
			}
			map.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
			super.unload();
		}

		protected function mouseMoveHandler(event:MouseEvent):void
		{
			where=map.toMapPoint(new Point(event.stageX - map.x, event.stageY - map.y));
		}

	}
}
